const BaseService = require('./base')
const { Op } = require('sequelize')
const { throws } = require('power-assert')
class MenuService extends BaseService {
	constructor(...args) {
		super(...args)
		this.modelName = 'Menu'
	}
	async list2(options) {
		return await this.ctx.model.Menu.findAll(options)
	}
	async del(ids) {
		if (!Array.isArray(ids)) ids = [ids]
		let transaction
		try {
			// 建立事务对象
			transaction = await this.ctx.model.transaction()
			for (let i = 0; i < ids.length; i++) {
				const id = ids[i]
				const res2 = await this.ctx.model.RoleMenu.findOne({
					where: {
						mid: {
							[Op.eq]: id,
						},
					},
				})
				if (res2) {
					throw Error
				}

				await this.ctx.model[this.modelName].destroy({
					where: {
						id: {
							[Op.eq]: id,
						},
					},
					transaction,
				})
			}
			// 提交事务
			await transaction.commit()
			return { flag: true }
		} catch (error) {
			// 事务回滚
			await transaction.rollback()
			return { flag: false, msg: '数据存在关联', code: 400 }
		}
	}
	async update(obj) {
		//	权限表的更新 enabled 为 false 删除权限
		let transaction
		try {
			transaction = await this.ctx.model.transaction()
			const enabled = obj.enabled
			// 如果修改成了隐藏
			if (!enabled) {
				// 删除所有角色对应的prim权限
				// 找到了就删除

				let res = this.ctx.model.RoleMenu.destroy(
					{
						where: {
							prim: {
								[Op.eq]: obj.remark,
							},
						},
					},
					{
						transaction,
					}
				)
				if (!res) {
					throw Error
				}
			} else {
				// 添加权限进权限列表
				let res3 = this.ctx.model.RoleMenu.create({
					rid: 1,
					mid: obj.id,
					prim: obj.remark,
				})
				let res4 = this.ctx.model.RoleMenu.create({
					rid: 2,
					mid: obj.id,
					prim: obj.remark,
				})

				if (!res3 || !res4) {
					throw Error
				}
			}
			const res1 = await this.ctx.model.Menu.update(
				{ ...obj },
				{
					where: {
						id: {
							[Op.eq]: obj.id,
						},
					},
				},
				{ transaction }
			)
			if (!res1) {
				throw Error
			}
			await transaction.commit()
			return { flag: true }
		} catch (error) {
			await transaction.rollback()
			return { flag: false }
		}
	}
}

module.exports = MenuService
